var uuid = require('uuid/v4')
var crypto = require('crypto')
var deepcopy = require('deepcopy')
var config = require('../config.js')

var helper = {
    md5: function (v) {
        m = crypto.createHash('md5');
        m.update(v);
        return m.digest('hex');
    },
    midString: function (v) {
        return v.substring(1, v.length - 1);
    },
    uuid: function () {
        return uuid()
    },
    deepCopy: function (obj) {
        return deepcopy(obj)
    },
    getFormData: function (a) {
        var o = {}
        a.forEach(function (i, e, a) {
            if (o[i.name] !== undefined) {
                if (!o[i.name].push) {
                    o[i.name] = [o[i.name]]
                }
                o[i.name].push(i.value || '')
            } else {
                o[i.name] = i.value || ''
            }
        })
        return o
    }
}

Date.prototype.addDay = function (day) {
    this.setDate(this.getDate() + day)
    return this
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1)
                ? (o[k])
                : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
}

String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function () {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function () {
    return this.replace(/(\s*$)/g, "");
}

module.exports = helper
